package org.example.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.entity.Permission;
import org.example.entity.Role;
import org.example.entity.User;
import org.example.service.IPermissionService;
import org.example.service.IRoleService;
import org.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现UserDetailsService
 * 查询用户
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @Autowired
    IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String userCode)
            throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(User.USERCODE, userCode);
        User user = userService.getOne(queryWrapper);
        if (user != null) {
            //角色
            Role role = roleService.getOne(new QueryWrapper<Role>().eq(Role.ID, user.getUserRole()));
            List<Permission> permissions = permissionService.selectPermission(role.getId());
            List<String> authorities = new ArrayList<>();
            for (Permission permission : permissions) {
                authorities.add(permission.getCode());
            }
            authorities.add(role.getRoleCode());
            String[] authoritieArr = new String[authorities.size()];
            return org.springframework.security.core.userdetails.User
                    .withUsername(user.getUserCode())
                    .password(user.getUserPassword()) //这里不加密 数据库存储是加密后的密码
                    .authorities(authorities.toArray(authoritieArr)) //角色code
                    .build();
        }
        //没有查到用户 抛出异常
        throw new UsernameNotFoundException("用户名不存在!");
//        return null;
    }
}
